<?php
class Admin_IndexController extends Zend_Controller_Action
{
private $stdClass;
private $data;
	public function preDispatch()
	{}
    public function init(){
        $this->_helper->getHelper('AjaxContext')
            ->addActionContext('index','json')
            //->addActionContext('settings','json')
            ->initContext();
        //if($this->getRequest()->isXmlHttpRequest()){
           // $this->_helper->getHelper('layout')->disableLayout();
        //}
    }
	public function indexAction()
	{
		$q=Doctrine_Query::create()
			->from('Myblog_Model_Pages');
		$result=$q->execute();
        for($i=0;$i<count($q);$i++){
            $this->view->page=$result[$i];
        }
	}
	public function pageAction()
	{
	if($this->getRequest()->isGet())
		{
		$filters=array('page'=>array('HtmlEntities','StripTags','StringTrim'));
		$validators=array('page'=>array(array('InArray','haystack'=>array('main','about','contact','catalog'))));
		$url=$this->getRequest()->getRequestUri();
		$input=new Zend_Filter_Input($filters,$validators);
		$input->setData($this->getRequest()->getParams());
		if($input->isValid()){
			$q=Doctrine_Query::create()
				->from('Myblog_Model_Articles a')
				->where('page=?','/'.$input->page);
			$result=$q->execute();
			$this->view->item=$result;
		    }
	    }
    }
    public function getMainPageAction(){

        if($this->getRequest()->isXmlHttpRequest()){
            $this->_helper->getHelper('layout')->disableLayout();
            $pagename = $this->getRequest()->getParam('pagename');
            $firstLoad= $this->getRequest()->getParam('startpage');

            if($firstLoad=='first'){
                $startPage=0;
            }
            else{
                $firstLoad = false;
                $startPage = $this->getRequest()->getParam('startpage').'0';
            }
        if($startPage){
            $startPage = $startPage-10;
        }else{

        }
        $endPage = $this->getRequest()->getParam('limit');
        if(!$endPage){$endPage = 0;}
        $segment = array();
        $limit = 10;

        $getData = Myblog_Model_Articles::getTabdata($startPage,$endPage,$pagename);

            if($startPage == 0 ){
            $cnt = ceil(count($getData)/10);//окугляем до большего
                for($i=0;$i < $limit;$i++){
                    if(isset($getData[$i])){
                        $segment[] = $getData[$i];
                    }
                }

            $this->view->pages = $cnt;
            $this->view->page = $segment;
            $this->view->artcount = count($getData);

            }
            if($startPage && $endPage  || $firstLoad){

                $this->_helper->json($getData);
            }

        }
    }
    public function getArticlesAction(){
        if($this->getRequest()->isXmlHttpRequest()){
            $this->_helper->getHelper('layout')->disableLayout();
            $firstLoad= $this->getRequest()->getParam('startpage');
            if($firstLoad=='first'){
                $startPage=0;
            }
            else{
                $firstLoad = false;
                $startPage = $this->getRequest()->getParam('startpage').'0';
            }
            if($startPage){
                $startPage = $startPage-10;
            }else{

            }
            $endPage = $this->getRequest()->getParam('limit');
            if(!$endPage){$endPage = 0;}
            $segment = array();
            $limit = 10;
            $getData = Myblog_Model_Articles::getTabdata($startPage,$endPage,'articles');
            if($startPage == 0 ){
                $cnt = ceil(count($getData)/10);//окугляем до большего
                for($i=0;$i < $limit;$i++){
                    if(isset($getData[$i])){
                        $segment[]= $getData[$i];
                    }
                }

                $this->view->pages = $cnt;
                $this->view->page = $segment;
                $this->view->artcount = count($getData);
            }
            if($startPage && $endPage  || $firstLoad){

                $this->_helper->json($getData);
            }

        }
    }
    function getReviewsPageAction(){

        if($this->getRequest()->isXmlHttpRequest()){
            $this->_helper->getHelper('layout')->disableLayout();
            $firstLoad= $this->getRequest()->getParam('startpage');
            if($firstLoad=='first'){
                $startPage=0;
            }
            else{
                $firstLoad = false;
                $startPage = $this->getRequest()->getParam('startpage').'0';
            }
            if($startPage){
                $startPage = $startPage-10;
            }else{

            }
            $endPage = $this->getRequest()->getParam('limit');
            if(!$endPage){$endPage = 0;}
            $segment = array();
            $limit = 10;
            $getData = Myblog_Model_Articles::getTabdata($startPage,$endPage,'reviews');
            if($startPage == 0 ){
                $cnt = ceil(count($getData)/10);//окугляем до большего
                for($i=0;$i < $limit;$i++){
                    if(isset($getData[$i])){
                        $segment[]= $getData[$i];
                    }

                }

                $this->view->pages = $cnt;
                $this->view->page = $segment;
                $this->view->artcount = count($getData);
            }
            if($startPage && $endPage  || $firstLoad){

                $this->_helper->json($getData);
            }
        }
    }
    public function setVisibAction(){
        if($this->getRequest()->isXmlHttpRequest()){
            $this->_helper->getHelper('layout')->disableLayout();
                $post = $this->getRequest()->getPost();
                    $q = Doctrine_Query::create()
                        ->update('Myblog_Model_Articles a')
                        ->set('a.visibility','?',$post['value'])
                        ->where('a.article_id=?',$post['id'])
                        ->execute();
                    if($q){
                        $this->_helper->json(array('oper'=>'change_success'));
                    }
        }
    }
    public function informationAction(){
        /**
         * Created by JetBrains PhpStorm.
         * User: root
         * Date: 17.06.13
         * /admin/siteinfo | mod:admin,cont:index,action:informationAction | .
         */
        if($this->getRequest()->isXmlHttpRequest()){

            $getData = $this->getRequest()->getParam('data');
            if(isset($getData)){
                $auth = Zend_Auth::getInstance();
                $infoData = $auth->getIdentity()->data[0];
                unset($infoData['password'],$infoData['reg_time']);

                $q = Doctrine_Query::create()
                    ->from('Myblog_Model_Articles a')
                    ->leftJoin('a.Myblog_Model_Comments c')
                    ->select("a.article_id,a.visibility,COUNT(c.article_id) AS commcount,COUNT(c.visibility) AS sumcomm,SUM(c.visibility) AS countcomm")
                    ->groupby('a.article_id')
                    ->fetchArray();

                 $categories = Myblog_Model_Categories::getCategories();
                 $users = Myblog_Model_Users::getUsers();
                 $lastlogin = Doctrine_Query::create()
                            ->from('Myblog_Model_Admins a')
                            ->select('MAX(a.logintime) AS lastlogin')
                            ->where('a.user_id=?',$infoData['id'])
                            ->whereNotIn('a.logintime',array($infoData['logindatetime']))
                            ->fetchArray();
                $clearDB = Doctrine_Query::create()
                        ->from('Myblog_Model_Admins a')
                        ->delete()
                        ->where('a.logintime < ?',$lastlogin[0]['lastlogin'])
                        ->execute();

                if(count($q) >1){
                    $infoData['artcount'] = count($q);
                    $infoData['commentscount'] = 0;
                    $infoData['commentsvisibyes'] = 0;
                    $infoData['commentsvisibno'] = 0;
                    $infoData['sumscount'] = 0;
                    $infoData['artvisibno'] = 0;
                    $infoData['artvisibyes'] = 0;
                    for($i=0;$i < count($q);$i++){
                        $infoData['commentscount'] += $q[$i]['sumcomm'];
                        $infoData['commentsvisibyes'] += $q[$i]['countcomm'];
                        $infoData['commentsvisibno'] += $q[$i]['sumcomm']-$q[$i]['countcomm'];

                        if($q[$i]['visibility'] == 'no'){
                            $infoData['artvisibno'] +=1;
                        }
                    }
                    $infoData['artvisibyes'] = $infoData['artcount']-$infoData['artvisibno'];
                }

                $infoData['lastlogintime'] = $lastlogin[0]['lastlogin'];
                $infoData['categoriescount'] = count($categories);
                $infoData['userscount'] = count($users);
                $infoData['userip'] = $this->getRequest()->getClientIp();

                $this->_helper->json($infoData);
            }
        }
    }
    public function getLastResourceAction(){
        $get = Doctrine_Query::create()
             ->from('Myblog_Model_Articles a')
            ->select('a.article_id,a.page,a.created_dt')
            ->limit(5)
            ->orderby('a.created_dt DESC')
            ->fetchArray();
        if($get){
            $this->_helper->json($get);
        }else{
            $this->_helper->json(array('oper'=>'failed'));
        }

    }
    public function settingsAction(){

        $auth = Zend_Auth::getInstance()->getIdentity();
        if(isset($auth->data[0])){
            $this->view->data = $auth->data[0];
        }else{
            $this->view->notice = 'Для редактирования данных надо войти через /admin/login';
        }
        if($this->getRequest()->isXmlHttpRequest()){
            //отфильтровать данные
            $data = $this->getRequest()->getPost('data');
            $oper = $this->getRequest()->getPost('oper');
            $target = $this->getRequest()->getPost('target');
            $id = $this->getRequest()->getPost('id');

            if(isset($data) && isset($target) && isset($id) && $oper === 'update' && $auth->data[0][$target] !== $data){

                $q = Doctrine_Query::create()
                    ->update('Myblog_Model_Users u')
                    ->set('u.'.$target,'?',$data)
                    ->where('u.id=?',$id)
                    ->execute();
                if($q){
                    $auth->data[0][$target] = $data;
                    $this->_helper->json(array("oper"=>"success","data"=>$data));
                }else{
                    throw new Zend_Controller_Action_Exception('Invalid input');
                }
            }else{
                $this->_helper->json(array("oper"=>"failed","data"=>$data));
            }
        }
    }

}
